import tkinter
import socket
import time

class a:
    def __init__(self, root):
        root.geometry('500x500')
        self.udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_client.bind(('', 8081))
        self.address = ('192.168.0.107', 8080)

        self.T = tkinter.Text(root, width=50)
        self.T.place(x=20, y=20)
        self.T_2 = tkinter.Text(root, width=36, heigh=5)
        self.T_2.place(x=20, y=400)
        self.B = tkinter.Button(root, text='发送', command=self.send)
        self.B.place(x=295, y=400, width=80, heigh=70)
        self.B = tkinter.Button(root, text='接收', command=self.recv)
        self.B.place(x=380, y=400, width=80, heigh=70)

    def send(self):
        var = self.T_2.get('0.0', 'end')
        self.T.insert('end','我:' + '\n' + var)
        a.dele(self,var)

    def dele(self,var):
        self.T_2.delete('0.0', 'end')
        if var:
            a.sendto(self,var)
        else:
            pass

    def sendto(self,var):
        a = self.udp_client.sendto(var.encode('utf-8'),self.address)

    def recv(self):
        n = self.udp_client.recvfrom(1024)
        self.T.insert('end','对方:' + '\n' + n[0].decode('gbk'))

if __name__ == '__main__':
    root = tkinter.Tk()
    app = a(root)
    root.mainloop()